
package com.cptravel.tool;

import android.app.Activity;
import android.text.TextUtils;

import com.core.util.B5MActivityHelper;
import com.core.util.B5MCacheManage;
import com.core.util.B5MPreferenceHelper;
import com.core.util.B5MPreferenceKeys;
import com.cptravel.activity.LoginActivity;
import com.cptravel.application.MainApplication;
import com.cptravel.bean.User;
import com.google.gson.Gson;

public class UserInfoManage
{
    private User user;
    private boolean isLogined;
    private static UserInfoManage _instance;

    /**
     * 初始化用户信息
     * @param userString
     */
    public void saveUser(String userString)
    {
        if (!TextUtils.isEmpty(userString))
        {
            isLogined = true;
            user = new Gson().fromJson(userString, User.class);
            B5MPreferenceHelper.saveStringValue(MainApplication.getInstance(), B5MPreferenceKeys.USER_USERID, user.getUserid());
            B5MCacheManage.getInstance().saveObject(userString, "");
        }
        else
        {
            throw new NullPointerException("user is null");
        }
    }

    public User getUser()
    {
        if (isLogined)
        {
            if (user == null)
            {
                String userString = B5MCacheManage.getInstance().readObject("");
                if (!TextUtils.isEmpty(userString))
                {
                    return new Gson().fromJson(userString, User.class);
                }
            }
            else
            {
                return user;
            }
        }
        return null;
    }

    public boolean isLogined()
    {
        return isLogined;
    }

    public void clearData()
    {
        isLogined = false;
        user = null;
    }

    public static UserInfoManage getInstance()
    {
        synchronized (UserInfoManage.class)
        {
            if (_instance == null)
            {
                _instance = new UserInfoManage();
            }
        }
        return _instance;
    }

    public boolean checkIsLogined(Activity activity)
    {
        if (user != null && isLogined())
        {
            return true;
        }
        else
        {
            B5MActivityHelper.startActivity(activity, LoginActivity.class);
        }
        return false;
    }
}
